/*
 * @Description:
 * @Author: cgt
 * @Date: 2021-12-29 18:00:27
 * @LastEditors: cgt
 * @LastEditTime: 2021-12-30 15:32:10
 */
var date = require('./utils/date');
const fs = require('fs');
var Config = require('./Config');
var prettier = require('prettier');
const pretterOptions = {
  parser: 'babel'
};
/**
 * 备份api文件夹
 */
module.exports.backupApiFolder = function() {
  if (fs.existsSync(Config.API_FOLDER)) {
    let backupPath = Config.API_FOLDER.slice(0, -1) + '_' + date.getDateString() + Config.API_FOLDER.slice(-1);
    fs.renameSync(Config.API_FOLDER, backupPath);
    console.log('备份成功', backupPath);
  }
};
/**
 * 创建api文件夹
 */
module.exports.writeApiFolder = function(name) {
  console.log('创建API文件夹', Config.API_FOLDER + name);
  fs.mkdirSync(Config.API_FOLDER + name, { recursive: true });
};
/**
 * 写入api内容
 */
module.exports.writeApiContent = function(apiname, content) {
  var filepath = Config.API_FOLDER + apiname + '/index.js';
  fs.writeFile(filepath, prettier.format(content, pretterOptions), {}, (err) => {
    if (err) {
      console.log('写入接口文件出错 : ', filepath);
      throw err;
    }
    // console.log("write file success : ", filepath);
  });
};

/**
 * 写入具体接口类
 */
module.exports.writeCategory = function(apiname, categoryName, content) {
  // 分类文件名称
  var categoryFileName = categoryName + '.js';
  var filepath = Config.API_FOLDER + apiname + '/' + categoryFileName;
  fs.writeFile(filepath, prettier.format(content, pretterOptions), {}, (err) => {
    if (err) {
      console.log('写入接口分组出错: ', filepath);
      throw err;
    }
    // console.log("write file success : ", filepath);
  });
};

/**
 * 写入入口文件
 */
module.exports.writeEntry = function(content, cb) {
  var filepath = Config.ENTRY_FILE;
  console.log('准备写入入口文件', filepath);
  fs.writeFile(filepath, prettier.format(content, pretterOptions), {}, (err) => {
    if (err) {
      console.log('写入入口文件出错');
      throw err;
    }
    console.log('写入入口文件成功');
    if(cb) {
      cb();
    }
  });
};
